﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace MadProps
{
    public sealed class ClrMember
    {
        readonly FieldInfo field;
        readonly PropertyInfo property;
        readonly MemberInfo member;

        public ClrMember(FieldInfo field)
        {
            this.field = field.ThrowIfNull("field");
            this.member = field;

            this.Type = field.FieldType;

            Initialize();
        }
        public ClrMember(PropertyInfo property)
        {
            this.property = property.ThrowIfNull("property");
            this.member = property;

            this.Type = property.PropertyType;

            Initialize();
        }

        void Initialize()
        {
            this.DeclaringType = member.DeclaringType;
            this.Name = member.Name;
        }

        public Type Type { get; private set; }
        public Type DeclaringType { get; private set; }
        public string Name { get; private set; }

        public void SetValue(object target, object value)
        {
            if (property != null)
            {
                property.SetValue(target, value, null);
            }
            else if (field != null)
            {
                field.SetValue(target, value);
            }
        }

        public IEnumerable<Attribute> GetCustomAttributes(bool inherit)
        {
            return member.GetCustomAttributes(inherit).OfType<Attribute>();
        }
    }
}
